#include <linux/module.h>
#include <linux/kernel.h>
#define __NO_VERSION__
#include <rtai.h>
#include <rtai_sched.h>
#include <rtai_sem.h>
#include "rtai_shmem.h"

#define TASK_SLOT "taskslot0"

SEM task_sem_start;
SEM task_sem_done;
static RT_TASK task_handle;

int count = 0;

// 实时任务函数
static void kernel_test_task(long arg)
{
    rt_printk("Kernel test task started\n");
    while (1)
    {
        rt_sem_wait(&task_sem_start);
        count++;
        shmem_write("count1", &count);
        rt_sem_signal(&task_sem_done);
    }
    rt_printk("Kernel test task ended\n");
}

void task_func(void)
{ 
    rt_sem_signal(&task_sem_start);
    rt_sem_wait(&task_sem_done);
}

int init_module(void)
{
    unsigned long func_ptr = (unsigned long)task_func;

    rt_sem_init(&task_sem_start, 0);
    rt_sem_init(&task_sem_done, 0);
    
    // 初始化共享内存
    rtai_shmem_init();

    rt_task_init_cpuid(&task_handle, kernel_test_task, 0, 4096, 1, 0, NULL, 1);
    rt_task_resume(&task_handle);
    
    // 将任务函数指针写入共享内存
    shmem_write(TASK_SLOT, &func_ptr);

    shmem_register("count1", TYPE_UDINT, &count);
    
    printk("Kernel test module loaded\n");
    return 0;
}

void cleanup_module(void)
{
    // 清除任务槽
    unsigned long zero = 0;
    shmem_write(TASK_SLOT, &zero);

    rt_task_delete(&task_handle);

    rt_sem_delete(&task_sem_start);
    rt_sem_delete(&task_sem_done);
    
    shmem_unregister("count1");
    printk("Kernel test module unloaded\n");
}


